package com.demo02_interaction.controller;

import com.demo02_interaction.service.LikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/likes")
@RequiredArgsConstructor
public class LikeController {
    private final LikeService likeService;

    // 从请求头中获取用户ID（实际项目中应该从JWT token中解析）
    @PostMapping("/{videoId}")
    public ResponseEntity<String> likeVideo(@PathVariable Long videoId, HttpServletRequest request) {
        // 从请求头获取用户ID，实际项目中应该从JWT token中解析
        String userIdStr = request.getHeader("user-id");
        if (userIdStr == null || userIdStr.isEmpty()) {
            return ResponseEntity.badRequest().body("缺少用户ID");
        }
        
        try {
            Long userId = Long.parseLong(userIdStr);
            likeService.likeVideo(userId, videoId);
            return ResponseEntity.ok("点赞成功");
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body("用户ID格式错误");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @DeleteMapping("/{videoId}")
    public ResponseEntity<String> unlikeVideo(@PathVariable Long videoId, HttpServletRequest request) {
        // 从请求头获取用户ID，实际项目中应该从JWT token中解析
        String userIdStr = request.getHeader("user-id");
        if (userIdStr == null || userIdStr.isEmpty()) {
            return ResponseEntity.badRequest().body("缺少用户ID");
        }
        
        try {
            Long userId = Long.parseLong(userIdStr);
            likeService.unlikeVideo(userId, videoId);
            return ResponseEntity.ok("取消点赞成功");
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body("用户ID格式错误");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/{videoId}")
    public ResponseEntity<Long> getLikeCount(@PathVariable Long videoId) {
        Long likeCount = likeService.getLikeCount(videoId);
        return ResponseEntity.ok(likeCount);
    }
}